package com.stu.jsoup.nw.wx;

import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * @author MI
 * @ClassName GetWx.java
 * @createTime 2021年11月28日 12:58:00
 * 微信文章
 */
public class GetWx {

    @Test
    public void err() throws Exception {
        System.out.println(ConstantEnum.NO_SEQ.getMsg());
        errThrow();

    }

    public void errThrow() throws Exception {
        if (true) {
            // throw new Exception("error");
        }
        System.out.println("GetWx.errThrow");
    }

    @Test
    public void get() throws Exception {
        String url = "https://mp.weixin.qq.com/s/hG4BB7o5lVCyRJM060nATw";
        String path = "D:\\";
        // String path = "D:\\file\\gitfile\\pic\\D-微信公众号\\01-连岳";
        // String path = "D:\\file\\gitfile\\pic\\D-微信公众号\\06-书单";
        // String path = "D:\\file\\gitfile\\pic\\D-微信公众号\\01-花甲老头";
        for (String ur : Arrays.asList("https://xueqiu.com/3424385641/207693731")) {
            Connection.Response response = Jsoup.connect(ur).method(Connection.Method.GET).execute();
            System.out.println(response.statusCode());
            Document doc = Jsoup.parse(response.body());
            Element titleEle = doc.getElementById("activity-name");

            //替换名字，因为可能出现该名字不能创建文件夹
            String title = "";
            if (titleEle == null) {
                Elements otherTitle = doc.getElementsByTag("title");
                title = StringEscapeUtils.unescapeHtml4(otherTitle.text()).substring(0, 16);


                title = title.replaceAll("[/\\\\:*?|]", "_");
                title = title.replaceAll("[\"<>]", "'");
                FileUtils.writeStringToFile(Paths.get(path, title + ".html").toFile(), doc.html(), StandardCharsets.UTF_8);


            } else {
                title = titleEle.text();
                title = title.replaceAll("[/\\\\:*?|]", "_");
                title = title.replaceAll("[\"<>]", "'");
                FileUtils.writeStringToFile(Paths.get(path, title + ".html").toFile(), doc.html(), StandardCharsets.UTF_8);

            }
        }


    }
}
